<?php

namespace Yj\Generator;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Yj\Generator\Core\Dao\Generator;
use Yj\Generator\GeneratorCommand;
use Hyperf\Command\Annotation\Command;

#[Command]
class DaoCommand extends GeneratorCommand
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'yj:dao';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new  dao class';
    private Generator $generator;

    /**
     * @param Generator $generator
     */
    public function __construct(Generator $generator)
    {
        parent::__construct();
        $this->generator = $generator;
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $config = $this->createConfig();
        $Generator = $this->generator->create($config);
        $content = $Generator->render();

        if ($config->get('preview') == true) {
            $this->output->writeln($Generator->render());
        } else {

            $path = lcfirst($Generator->getNamespace()->getNamespace());

            $className = $Generator->getClassName()->getName() . '.php';

            if ($this->Exists($path, $className)) {
                $this->error("{$className}已经存在{$path}");
                return;
            }
            $this->getFilesFactory()->put($path . '/' . $className, $content);

            $this->output->writeln(sprintf('Model %s generated', $path . '\\' . $className));
        }
    }

    protected function Exists($path, $className)
    {
        return $this->getFilesFactory()->has($path . '\\' . $className);
    }

    protected function getArguments()
    {
        return [
            ['class_name', InputArgument::REQUIRED, 'The class_name of the class'],
            ['dirname', InputArgument::OPTIONAL, 'The dirname of the class', false],
            ['preview', InputArgument::OPTIONAL, 'The preview of the class', false],
        ];
    }


    public function createConfig()
    {
        $config = [];
        foreach ($this->getArguments() as $argument) {
            $config[$argument[0]] = $this->argument($argument[0]);
        }
        return new \Yj\Generator\Core\Dao\Config($config);
    }
}